<script setup>
import { ref, watch, onMounted, } from 'vue';
import { queryClazzApi, addClazzApi, queryByIdApi,updateClazzApi, deleteClazzApi } from '@/api/clazz';
import {queryAllEmpApi} from '@/api/emp'
import { ElMessage, ElMessageBox } from 'element-plus';

//班级表单
const searchClazz = ref({
  name: '',
  date: [],
  begin: '',
  end: ''
});

//班级列表
const clazzList = ref([]);

const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

const handleSizeChange = (val) => {
  search();
}
const handleCurrentChange = (val) => {
  search();
}

//查询
const search = async () => {
  const result = await queryClazzApi(searchClazz.value.name,
                                     searchClazz.value.begin,
                                     searchClazz.value.end,
                                     currentPage.value,
                                     pageSize.value
  );
      if (result.code) {
        clazzList.value = result.data.rows;
        total.value = result.data.total;
      }
}

//查询所有班主任
const getAllEmp = async ()=>{
  const result = await queryAllEmpApi();
  if(result.code){
    emps.value = result.data;
  }
}
//钩子函数
onMounted(() => {
  search();
  getAllEmp();
})

// 清空
const clear = () => {
  searchClazz.value = {
    name: '',
    date: [],
    begin: '',
    end: ''
  }
  search();
}
//watch侦听
watch(() => searchClazz.value.date, (newVal, oldVal) => {
  if (searchClazz.value.date && searchClazz.value.date.length > 0) {
    searchClazz.value.begin = searchClazz.value.date[0];
    searchClazz.value.end = searchClazz.value.date[1];
  } else {
    searchClazz.value.begin = '';
    searchClazz.value.end = '';
  }
})

const dialogFormVisible = ref(false)
const dialogTitle = ref('')
// 新增班级

const emps = ref([]);
const subjects = ref(['java','前端','大数据','Python','Go','嵌入式']);

const clazz = ref({
  name:'',
  room:'',
  beginDate:'',
  endDate:'',
  masterId:'',
  masterName:'',
})
//校验信息
const clazzFormRef = ref();
const rules = ref({
    name: [
      { required: true, message: '班级名称为必填项', trigger: 'blur' },
    ],
    room: [
      { required: true, message: '班级教室为必填项', trigger: 'blur' },
    ],
    beginDate: [
      { required: true, message: '开课时间为必填项', trigger: 'change' },
    ],
    endDate: [
      { required: true, message: '结课时间为必填项', trigger: 'change' },
    ],
    subject: [
      { required: true, message: '学科为必填项', trigger: 'change' },
    ],
})
//添加
const addClazz = async () => {
  dialogFormVisible.value = true;
  dialogTitle.value = '新增班级';
  clazz.value = {
    name:'',
    room:'',
    beginDate:'',
    endDate:'',
    masterId:'',
    masterName:'',
  }
  if(clazzFormRef.value){
    clazzFormRef.value.resetFields();
  }
}
//保存
const save = async ()=>{
  if(!clazzFormRef) return;
  await clazzFormRef.value.validate(async (valid,fields)=>{
    if(valid){//通过
      let result;
      if(clazz.value.id){
        result = await updateClazzApi(clazz.value);
      }else{
        result = await addClazzApi(clazz.value);
      }
      if(result.code){
        ElMessage.success('保存成功');
        dialogFormVisible.value = false;
        search();
      }else{
        ElMessage.error(result.msg);
      }
    }else{//不通过
      ElMessage.error('表单校验不通过,请检查表单');
    }
  })
}
//数据回显
const edit = async (id)=>{
  const result = await queryByIdApi(id);
  if(result.code){
    dialogFormVisible.value = true;
    dialogTitle.value = '修改员工';
    clazz.value = result.data;
  }
}
//删除员工
const deleteById = async (id)=>{
    ElMessageBox.confirm(
    '您确定删除该班级吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      center: true,
    }
  ).then( async () => {//确认
      const result = await deleteClazzApi(id);
      if(result.code){//删除成功
        ElMessage.success('删除成功')
        search();
      }else{//删除失败
        ElMessage.error(result.msg);
      }
    })
    .catch(() => {//取消
      ElMessage.info('操作已取消');
    })
  }
</script>

<template>
  <h1>班级管理</h1>
  <!-- 搜索表单 -->
  <div class="search">
    <el-form :inline="true" :model="searchClazz" class="demo-form-inline">
      <el-form-item label="班级名称">
        <el-input v-model="searchClazz.name" placeholder="请输入班级名称" />
      </el-form-item>
      <el-form-item label="结课时间">
        <el-date-picker v-model="searchClazz.date" type="daterange" range-separator="至" start-placeholder="开始时间"
          end-placeholder="结束时间" value-format="YYYY-MM-DD" />
      </el-form-item>
      <el-form-item id="clbutton">
        <el-button type="primary" @click="search">查询</el-button>
        <el-button type="info" @click="clear">清空</el-button>
      </el-form-item>
    </el-form>
  </div>
  <el-button type="primary" @click="addClazz">新增班级</el-button>
  <!-- 班级列表 -->
  <div class="clazzFrom">
    <el-table :data="clazzList" border style="width: 100%">
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="name" label="班级名称" width="180" align="center" />
      <el-table-column prop="room" label="班级教室" width="100" align="center" />
      <el-table-column prop="masterName" label="班主任" width="100" align="center">
      </el-table-column>
      <el-table-column prop="beginDate" label="开课时间" width="150" align="center" />
      <el-table-column prop="endDate" label="结课时间" width="150" align="center" />
      <el-table-column prop="status" label="状态" width="130" align="center">
      </el-table-column>
      <el-table-column prop="updateTime" label="最后修改时间" align="center" />
      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
          <el-button size="small" type="primary" @click="edit(scope.row.id)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteById(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 分页条 -->
  <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40, 50]"
    layout="total, sizes, prev, pager, next, jumper" :total="total" 
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange" />
  <!-- 新增/修改班级对话框 -->
  <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="500">
    <el-form :model="clazz" ref="clazzFormRef" :rules="rules">

        <el-form-item label="班级名称" label-width="80px" prop="name">
          <el-input v-model="clazz.name" placeholder="请输入班级名称" style="width: 100%"/>
        </el-form-item>
  
        <el-form-item label="班级教室" label-width="80px" prop="room">
          <el-input v-model="clazz.room" placeholder="请输入班级教室" style="width: 100%"/>
        </el-form-item>

        <el-form-item label="开课时间" label-width="80px" prop="beginDate">
          <el-date-picker v-model="clazz.beginDate" type="date" placeholder="请选择开课时间" style="width: 100%"
          format="YYYY-MM-DD" value-format="YYYY-MM-DD"/>
        </el-form-item>
   
        <el-form-item label="结课时间" label-width="80px" prop="endDate">
          <el-date-picker v-model="clazz.endDate" type="date" placeholder="请选择结课时间" style="width: 100%"
          format="YYYY-MM-DD" value-format="YYYY-MM-DD"/>
        </el-form-item>

        <el-form-item label="班主任" label-width="80px">
          <el-select v-model="clazz.masterId" placeholder="请选择班主任" style="width: 100%">
            <el-option v-for="emp in emps" :label="emp.name" :value="emp.id" />
          </el-select>
        </el-form-item>

          <el-form-item label="学科" label-width="80px" prop="subject">
            <el-select v-model="clazz.subject" placeholder="请选择学科" style="width: 100%">
              <el-option v-for="(subject, index) in subjects" :key="index" :label="subject" :value="index" />
            </el-select>
          </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="save">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.search {
  margin-top: 10px;
  margin-bottom: 10px;
}

#clbutton {
  margin-left: 88px;
}

.clazzFrom {
  margin-top: 10px;
  margin-bottom: 10px;
}
</style>